package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.pojo.*
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class IntegralDetailsRepository {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL).addConverterFactory(
                GsonConverterFactory.create()
            )
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun getAllIntegralDetailsById(id: Int): LiveData<MutableList<IntegralDetails>> {
        val params = mapOf("sfNumber" to id)
        val responseLiveData = MutableLiveData<MutableList<IntegralDetails>>(mutableListOf())
        httpApi.getAllIntegralDetailsByUserId(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    if (it.success && it.data["IntegralDetails"] != null) {
                        try {
                            val integralDetailsList =
                                GsonUtils.fromJson<MutableList<IntegralDetails>>(
                                    it.data["IntegralDetails"].toString(),
                                    object : TypeToken<MutableList<IntegralDetails>>() {}.type
                                )
                            responseLiveData.value = integralDetailsList
                        } catch (e: Error) {
                            e.printStackTrace()
                        }
                    } else LogUtils.e("获得全部积分明细http返回值的data为null!")
                } ?: LogUtils.e("获得全部积分明细http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun getTotalIntegralRanking(id: Int): LiveData<MutableMap<String, Any>> {
        val responseLiveData = MutableLiveData<MutableMap<String, Any>>()
        httpApi.getTotalIntegralRanking(mapOf("sfNumber" to id)).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    if (it.success) {
                        try {
                            val userList = GsonUtils.fromJson<MutableList<User>>(
                                it.data["all"].toString(),
                                object : TypeToken<MutableList<User>>() {}.type
                            )
                            val leaderboard = GsonUtils.fromJson<Leaderboard>(
                                it.data["rank"].toString(),
                                object : TypeToken<Leaderboard>() {}.type
                            )
                            if (userList != null && userList.size > 0 && leaderboard != null) {
                                responseLiveData.value =
                                    mutableMapOf(
                                        "userList" to userList,
                                        "leaderboard" to leaderboard
                                    )
                            } else {
                                LogUtils.e("解析出的东西中为空！")
                                responseLiveData.value = mutableMapOf()
                            }
                        } catch (e: Error) {
                            e.printStackTrace()
                        }
                    } else {
                        LogUtils.e(it.message)
                        responseLiveData.value = mutableMapOf()
                    }
                } ?: LogUtils.e("获取总的积分排行榜http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun getYearIntegralRanking(id: Int): LiveData<MutableMap<String, Any>> {
        val responseLiveData = MutableLiveData<MutableMap<String, Any>>()
        httpApi.getYearIntegralRanking(mapOf("sfNumber" to id)).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    if (it.success) {
                        try {
                            val userList = GsonUtils.fromJson<MutableList<User>>(
                                it.data["year"].toString(),
                                object : TypeToken<MutableList<User>>() {}.type
                            )
                            val leaderboard = GsonUtils.fromJson<Leaderboard>(
                                it.data["rank"].toString(),
                                object : TypeToken<Leaderboard>() {}.type
                            )
                            if (userList != null && userList.size > 0 && leaderboard != null) {
                                responseLiveData.value =
                                    mutableMapOf(
                                        "userList" to userList,
                                        "leaderboard" to leaderboard
                                    )
                            } else {
                                LogUtils.e("解析出的东西中为空！")
                                responseLiveData.value = mutableMapOf()
                            }
                        } catch (e: Error) {
                            e.printStackTrace()
                        }
                    } else {
                        LogUtils.e(it.message)
                        responseLiveData.value = mutableMapOf()
                    }
                } ?: LogUtils.e("获取年度积分排行榜http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }
}